import operate from '../utils/operate.js'

export default class Request {
    http(param) {
        // 请求参数
        let token = "", header = {}
        if (param.isToken || param.isToken == null) {
            token = uni.getStorageSync('token')
            header["Authorization"] = "Bearer " + token
        }
        let url = param.url, method = param.method, data = param.data || {}, hideLoading = param.hideLoading || false;

        const requestUrl = operate.api + url;

        header["content-type"] = "application/json"

        if (!hideLoading) {
            uni.showLoading({
                title: '加载中...'
            });
        }
        return new Promise((resolve, reject) => {
            uni.request({
                url: requestUrl, data: data, method: method, header: header, success: (res) => {
                    if (res.data.code === 401) {
                        uni.showToast({
                            title: "未登录或已过期", duration: 2000, icon: "error"
                        })
                        uni.reLaunch({url: '/pages/login/login?expired=true'})
                    } else if (res.data.code === 500 || res.statusCode && res.statusCode !== 200) {
                        uni.showToast({
                            title: "api错误" + res.errMsg, icon: 'error'
                        });
                        return;
                    }
                    resolve(res.data)
                }, fail: (e) => {
                    uni.showToast({
                        title: "" + e.data.msg, icon: 'error'
                    });
                    resolve(e.data);
                }, complete() {
                    if (!hideLoading) {
                        uni.hideLoading();
                    }
                    resolve()
                }
            })
        })
    }
}
